from django.contrib import admin
import datetime

from import_export.formats import base_formats

from .models import ArticleCategory, ArticleKeyword, Article, AIExcelFile, UserKeywordFocus
from init_data.import_data import ArticleImporter
from mptt.admin import DraggableMPTTAdmin
from import_export import resources
from import_export.admin import ExportActionMixin

articleExcelImporter = ArticleImporter()


class ArticleResource(resources.ModelResource):

    def get_export_headers(self):
        headers = ["标题", "标题链接", "缩略图", '时间', "正文内容", "摘要", "关键词", "分类", "关键内容", "风险判断",
                   "作者", "来源"]

        return headers

    class Meta:
        model = Article
        fields = ('title', 'url', 'thumb', 'public_time', 'content', 'abstract',
                  'keywords_raw', 'categories_raw', "keyword_contents", 'risk',
                  'author', 'article_source')


@admin.register(ArticleCategory)
class ArticleCategoryAdmin(DraggableMPTTAdmin):
    list_display = ('tree_actions', 'indented_title',)

    change_form_template = "admin/category_change_template.html"

@admin.register(ArticleKeyword)
class ArticleKeywordAdmin(admin.ModelAdmin):
    list_display = ('id', 'keyword_preview', 'keyword_value_preview', 'keyword_articles_preview')
    search_fields = ('text', 'id')
    actions = ['update_keyword_count_action', 'update_keyword_action', ]

    def update_keyword_count_action(self, request, queryset):
        # 处理自定义操作1的逻辑
        keywords = ArticleKeyword.objects.all()
        for k in keywords:
            k.value = k.article_set.count()
            k.save()

    def update_keyword_action(self, request, queryset):
        # 处理自定义操作1的逻辑
        ArticleKeyword.objects.all().delete()
        articles = Article.objects.all()
        add_or_create_articles_keywords_set = set()

        #
        for article in articles:
            # 如果关键词原字符串不为空
            article.keywords.set(articleExcelImporter.get_keywords_id(article.keywords_raw))
            article_keywords = article.keywords.all()
            add_or_create_articles_keywords_set.update(article_keywords)
            #  导入文章的同时需要同步统计文章关键词出现次数
        for keyword in add_or_create_articles_keywords_set:
            keyword.value = keyword.article_set.count()
            keyword.save()

    update_keyword_action.short_description = "重新生成关键词"


@admin.register(UserKeywordFocus)
class UserKeywordFocusAdmin(admin.ModelAdmin):
    list_display = ('user_preview', 'event')


@admin.register(Article)
class ArticleAdmin(ExportActionMixin, admin.ModelAdmin):
    resource_class = ArticleResource
    list_display = (
        'id', 'title_preview', 'url_preview', 'public_time', 'create_at', 'thumb_preview', 'abstract_preview',
        'content_preview',
        'keywords_preview', 'category_preview', 'keyword_contents_preview', 'risk_preview',
        'author', 'article_source')

    list_filter = ['risk', 'category', 'create_at']
    search_fields = ('title', 'abstract', 'content', 'keywords__text', 'keyword_contents', 'author', 'article_source')
    formats = [base_formats.XLSX]

    actions = ['delete_all_article_action', ]
    change_list_template = "admin/excel_changelist.html"

    def get_export_filename(self, request, queryset, file_format):
        today = datetime.datetime.today()
        return f'{today.strftime("%y_%m_%d")}.xlsx'  # 自定义文件名

    @admin.action(description="删除所有文章、分类、关键词、excel文件数据")
    def delete_all_article_action(self, request, queryset):
        # 处理自定义操作1的逻辑
        Article.objects.all().delete()
        ArticleCategory.objects.all().delete()
        ArticleKeyword.objects.all().delete()
        AIExcelFile.objects.all().delete()


@admin.register(AIExcelFile)
class AIExcelFileAdmin(admin.ModelAdmin):
    list_display = ('id', 'file', 'sync_status', 'updated_at')
    list_filter = ('sync_status',)
    actions = ["sync_excel_data_action", "sync_all_excel_data_action", "delete_all_excel_action"]
    search_fields = ('file',)

    def delete_all_excel_action(self, request, queryset):
        # 处理自定义操作1的逻辑
        AIExcelFile.objects.all().delete()

    def sync_excel_data_action(self, request, queryset):
        for excel in queryset:
            articleExcelImporter.import_data(file_name=excel.file)
            excel.sync_status = True
            excel.save()

    def sync_all_excel_data_action(self, request, queryset):
        for excel in AIExcelFile.objects.all():
            articleExcelImporter.import_data(file_name=excel.file)
            excel.sync_status = True
            excel.save()

    delete_all_excel_action.short_description = '删除所有对象'
    sync_excel_data_action.short_description = "重新导入选择文件"
    sync_all_excel_data_action.short_description = "重新导入所有已上传文件"
